package entity.units;

import java.util.LinkedList;

import entity.building.Building;
import levels.PathFinder;
import loading.ImageLoader;
import math.Vector2D;

public abstract class Worker extends GroundUnit
{
	protected static final int BUILDING = 2;
	
	private LinkedList<Building> buildingQueue;

	public Worker( Vector2D pos, ImageLoader img, PathFinder pf, double timeToTrain, int totalHealth )
	{
		super( pos, img, pf, timeToTrain, totalHealth );
		
		buildingQueue = new LinkedList<Building>();
	}
	
	public void build( Building b )
	{	
		if( buildingQueue.isEmpty() )
			super.goTo( Vector2D.subtract( b.getTopLeftCorner(), new Vector2D( 2, 2 ) ) );
		
		buildingQueue.add( b );
		
	}
	
	public void cancelBuildingQueue()
	{
		buildingQueue.clear();
	}
	
	/**
	 * This goTo() method cancels the building queue because the user right clicked and sent the builder to do something else
	 */
	public void goTo( Vector2D end )
	{
		super.goTo( end );
		
		this.cancelBuildingQueue();
	}
	
	public void update( double duration )
	{
		super.update( duration );
		
		if( !buildingQueue.isEmpty() && this.getState() == STANDING )
		{
			this.setState( BUILDING );
		}
		
		if( this.getState() == BUILDING )
		{
			if( buildingQueue.get( 0 ).isBuilt() )
			{
				buildingQueue.remove( 0 );
				
				if( buildingQueue.isEmpty() )
				{
					this.setState( STANDING );
				}
				else
				{
					super.goTo( Vector2D.subtract( buildingQueue.get( 0 ).getTopLeftCorner(), new Vector2D( 2, 2 ) ) );
				}
			}
			else
			{
				buildingQueue.get( 0 ).incTimeBuilding( duration );
			}
		}
	}
}
